package org.bonorsoft.modules.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.api.ISysBaseAPI;
import org.bonorsoft.common.system.util.JwtUtil;
import org.bonorsoft.common.util.PasswordUtil;
import org.bonorsoft.common.util.RedisUtil;
import org.bonorsoft.common.util.WxUtil;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.control.entity.Unit;
import org.bonorsoft.modules.system.entity.UserAudit;
import org.bonorsoft.modules.control.service.IUnitService;
import org.bonorsoft.modules.system.service.IUserAuditService;
import org.bonorsoft.modules.system.entity.SysUser;
import org.bonorsoft.modules.system.service.ISysUserService;
import org.bonorsoft.modules.wechat.service.ICodeService;
import org.bonorsoft.modules.wechat.vo.SysUserVo;
import org.bonorsoft.modules.sysutils.redisutil.RedisOperate;
import org.bonorsoft.modules.wechat.entity.WxAuthModel;
import org.bonorsoft.modules.wechat.entity.WxNormalModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@RestController
@RequestMapping("/wechat")
@Slf4j
public class WxLoginController {
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ICodeService codeService;
    @Autowired
    private IUnitService unitService;
    @Autowired
    private IUserAuditService userAuditService;

    /**
     * 微信小程序手机号码授权登陆
     * 有手机号码直接登陆，
     * 无手机号码有两种情况：1、用户根本不存在；2、用户没有填写手机号码  -- 跳转到小程序登陆界面
     *
     * @param wxLoginModel
     * @return
     */
    @GetMapping("/auth/login")
    public Result<JSONObject> login(@Validated WxAuthModel wxLoginModel) {
        log.info("{}", wxLoginModel);
        String session_key = wxLoginModel.getSession_key();
        String encryptedData = wxLoginModel.getEncryptedData();
        String iv = wxLoginModel.getIv();
        String v_result = WxUtil.analysisPhoneNumber(session_key, encryptedData, iv);
        JSONObject resultObject = JSONObject.parseObject(v_result);
        String purePhoneNumber = resultObject.getString("purePhoneNumber");//没有区号的手机号
        String phoneNumber = resultObject.getString("phoneNumber");//用户绑定的手机号（国外手机号会有区号）
        String countryCode = resultObject.getString("countryCode");//区号

        Result<JSONObject> result;

        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByPhone(purePhoneNumber);
        result = sysUserService.checkUserIsEffectiveWithWx(sysUser, purePhoneNumber);
        if (!result.isSuccess()) {
            return result;
        }

        //登陆之前判断redis中是否还存在缓存信息（防止意外退出情况）
        //RedisOperate.removeUser(sysUser);

        //用户登录信息
        userInfo(sysUser, result);

        //判断用户是否存在openid
        if (oConvertUtils.isEmpty(sysUser.getOpenid()))
            sysUserService.updateById(sysUser.setOpenid(wxLoginModel.getOpenid())
                    .setUnionid(wxLoginModel.getUnionid()));

        sysBaseAPI.addLog(sysUser.getUsername() + "/微信小程序", CommonConstant.LOG_TYPE_1, CommonConstant.OPERATE_TYPE_7);

        return result;
    }


    /**
     * 微信小程序用户名和密码登陆
     *
     * @param normalModel
     * @return
     */
    @RequestMapping(value = "/normal/login", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> login(@RequestBody WxNormalModel normalModel) {
        String username = normalModel.getUsername();
        String password = normalModel.getPassword();
        Result<JSONObject> result;

        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByName(username);
        result = sysUserService.checkUserIsEffective(sysUser);
        if (!result.isSuccess()) {
            return result;
        }

        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }
        //登陆之前判断redis中是否还存在缓存信息（防止意外退出情况）
        RedisOperate.removeUser(sysUser);
        //用户登录信息
        userInfo(sysUser, result);
        //判断用户是否存在openid
//        if (oConvertUtils.isEmpty(sysUser.getOpenid()))
//            sysUserService.updateById(sysUser.setOpenid(normalModel.getOpenid())
//                    .setUnionid(normalModel.getUnionid()));
        sysBaseAPI.addLog(sysUser.getUsername() + "/微信小程序", CommonConstant.LOG_TYPE_1, CommonConstant.OPERATE_TYPE_7);
        return result;
    }

    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    private Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
        String syspassword = sysUser.getPassword();
        String username = sysUser.getUsername();
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        JSONObject obj = new JSONObject();
        obj.put("token", token);
        obj.put("userInfo", sysUser);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }

    /**
     * 小程序端 群众用户 注册
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/masses/logon", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> logon(@RequestBody SysUser user) {
        UserAudit userAudit = new UserAudit();
        userAudit.setUsername(user.getUsername())
                .setRealname(user.getRealname())
                .setPassword(user.getPassword())
                .setPhone(user.getPhone())
                .setSex(user.getSex())
                .setRemark(user.getRemark())
                .setCreateTime(new Date());
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUsername())) || UserConstants.USER_NAME_NOT_UNIQUE.equals(userAuditService.checkUserNameUnique(user.getUsername()))) {
            return Result.error("用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)) || UserConstants.USER_PHONE_NOT_UNIQUE.equals(userAuditService.checkPhoneUnique(userAudit))) {
            return Result.error("用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        userAuditService.save(userAudit);
        return Result.ok("注册成功！请等待审核");
    }

    /**
     * 小程序端 企业业主 注册
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/enterprise/logon", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> logon(@RequestBody SysUserVo user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUsername()))) {
            return Result.error("用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return Result.error("用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        String code = user.getEnterpriseCode();
        if (oConvertUtils.isNotEmpty(code)) {
            if (unitService.count(new QueryWrapper<Unit>().eq("zzjgdm", code)) > 0) {
                codeService.addCode(user.getUsername(), code);
                String[] enterprise = new String[]{"09dc11be2112d3dba7979d45bc1f2804"};//企业业主权限
                sysUserService.add(user, enterprise);
                return Result.ok("注册成功！");
            } else {
                return Result.error("注册失败！企业组织机构代码不存在或未采集！");
            }
        } else {
            return Result.error("注册失败！企业组织机构代码不能为空！");
        }
    }

}
